package com.zizy.healthexpert.Activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.zizy.healthexpert.Adapter.listAddedDishesAdapter;
import com.zizy.healthexpert.Adapter.listResultAdapter;
import com.zizy.healthexpert.Config.Config;
import com.zizy.healthexpert.Database.DatabaseHelper;
import com.zizy.healthexpert.Database.MyDataBase_T_FOODS;
import com.zizy.healthexpert.Database.MyDataBase_T_FOODS_NUTRITION;
import com.zizy.healthexpert.Database.MyDatabase_Dishes;
import com.zizy.healthexpert.Practical.Practical;
import com.zizy.healthexpert.R;
import com.zxing.activity.CaptureActivity;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.logging.Handler;

public class SearchActivity extends ActionBarActivity {
    ListView listView;
    listResultAdapter myAdapter;
    LinkedHashSet<listResultAdapter.SearchFoodResult> resultList = new LinkedHashSet<listResultAdapter.SearchFoodResult>();
    LinkedHashSet<String> onlyOneNameSearchedContainer = new LinkedHashSet<String>();//if you want to show all result,del this.
    public static int mode = Config.SEARCH; // mode :    Search/Choose but only shared to listResultAdapter.
    private Bundle bundle = new Bundle();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        listView = (ListView) findViewById(R.id.listResult);
    }


    public void btnQRCodeClicked(View v) {
        Intent openCameraIntent = new Intent(SearchActivity.this, CaptureActivity.class);
        startActivityForResult(openCameraIntent, 0);

    }

    /*RESULT!!!!!!!!!!!!!!!!!!!!!!!*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*when return QR results*/
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            String dishesName = scanResult.split(";")[0];
            String noTitleResult = scanResult.substring(scanResult.indexOf(";") + 1, scanResult.length());//no dishes name
            String[] matArr = noTitleResult.split(";");
            /*ListView*/
            int isGoodToEat = Config.NOT_BAD_TO_EAT;

            resultList = new LinkedHashSet<listResultAdapter.SearchFoodResult>();
            resultList.add(new listResultAdapter.SearchFoodResult(dishesName, isGoodToEat, Config.QR_ID, Config.QR_FOOD));
//                /*set adapter*/
//            myAdapter = new listResultAdapter(getApplicationContext(),
//                    R.layout.list_search_result,new ArrayList(resultList));
//                /*set listView*/
//            listView.setAdapter(myAdapter);
            /*Bundle*/
            bundle.putInt("foodID", Config.QR_ID);
            HashMap<Integer, Integer> matMap = new HashMap<Integer, Integer>();
            ArrayList<Integer> matList = new ArrayList<Integer>();

            for (String mat : matArr) {
                if (mat.split(",") == null) continue;
                if (mat.split(",").equals("")) continue;
                int matID = Integer.parseInt(mat.split(",")[0]);
                int matValue = Integer.parseInt(mat.split(",")[1]);
                matMap.put(matID, matValue);
                matList.add(matID);
            }
            isGoodToEat = Practical.isFoodSuitable(matList, getApplicationContext());
            bundle.putSerializable("materialMap", matMap);
            bundle.putInt("isGoodToEat", isGoodToEat);

            switch (mode) {//TODO
                case Config.SEARCH:
                    /*open show_foods detail*/
                    bundle.putString(Config.bundle.DISHES_NAME, dishesName);
                    bundle.putString(Config.bundle.MAIN_INGREDIENT, noTitleResult);
                    Intent intent = new Intent(SearchActivity.this, FoodDetailActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                case Config.CHOOSE:
                    /*open add*/
                    //Config.recordFoodsActivity.viewItems.clear();
                    String formattedNut = "";//TODO
                    for (String str : noTitleResult.split(";")) {
                        int foodID = Integer.parseInt(str.split(",")[0]);
                        MyDataBase_T_FOODS_NUTRITION myDataBase_t_foods_nutrition = new MyDataBase_T_FOODS_NUTRITION(getApplicationContext());
                        ArrayList<MyDataBase_T_FOODS_NUTRITION.T_FOODS_NUTRITION> nutList = myDataBase_t_foods_nutrition.SearchT_FOODS_NUTRITION("*", String.format("FOOD_ID= %d ", foodID));
                        for (Iterator iterator = nutList.iterator(); iterator.hasNext(); ) {
                            MyDataBase_T_FOODS_NUTRITION.T_FOODS_NUTRITION nut = (MyDataBase_T_FOODS_NUTRITION.T_FOODS_NUTRITION) iterator.next();
                            formattedNut += nut.NUTRITION_ID + "," + nut.CONENT_VALUE + ";";
                        }
                    }
                    Config.recordFoodsActivity.viewItems.add(new listAddedDishesAdapter.addedDishes(dishesName, Config.QR_ID, formattedNut));

                    startActivity(new Intent(SearchActivity.this, RecordFoodsActivity.class));
                    this.finish();
                    break;
            }
        }
    }

    public void checkPersonalInformation() {
         /*Check personal Information*/
        if ((!Practical.isPersonalInfExist(getApplicationContext()))) {
            ((Activity) this).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "填寫疾病資料", Toast.LENGTH_SHORT).show();
                }
            });
        }


    }

    //click event : search button
    public void btnStartSearchClicked(View view) throws InterruptedException {


        Toast.makeText(getApplicationContext(), "請稍等，正在搜索中……", Toast.LENGTH_SHORT).show();


        /*clean*/
        resultList = new LinkedHashSet<listResultAdapter.SearchFoodResult>();
        onlyOneNameSearchedContainer = new LinkedHashSet<String>();//if you want to show all result,del this.cause there are some record are in same name
        ///*switch search mode*/
        //switch (((RadioGroup)findViewById(R.id.searchOptionGroup)).getCheckedRadioButtonId()){

        /*SearchMix: //both search dishes and material*/

        final int[] i = {0};
        new Thread(new Runnable() {
            @Override
            public void run() {
                doSearchMaterial();
                        /*set adapter*/
                myAdapter = new listResultAdapter(SearchActivity.this,
                        R.layout.list_search_result, new ArrayList(resultList));
                        /*set listView*/
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listView.setAdapter(myAdapter);

                    }
                });

                i[0]++;
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                doSearchDishes();
                        /*set adapter*/
                myAdapter = new listResultAdapter(SearchActivity.this,
                        R.layout.list_search_result, new ArrayList(resultList));
                        /*set listView*/
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listView.setAdapter(myAdapter);
                        Toast.makeText(getApplicationContext(), "搜索完成", Toast.LENGTH_SHORT).show();
                        checkPersonalInformation();

                    }
                });

                i[0]++;
            }
        }).start();
        //while (i[0] < 2) ;
    }
//        /*set adapter*/
//        myAdapter = new listResultAdapter(getApplicationContext(),
//                R.layout.list_search_result,new ArrayList(resultList));
//        /*set listView*/
//        listView.setAdapter(myAdapter);


    /**
     * Search Dishes
     */
    public void doSearchDishes() {
        /*get word*/
        String keyword = ((EditText) findViewById(R.id.editKeyword)).getText().toString();
//        ((EditText)    findViewById(R.id.editKeyword)).setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                Toast.makeText(getApplicationContext(),String.valueOf(actionId),Toast.LENGTH_SHORT).show();
//                Toast.makeText(getApplicationContext(),String.valueOf(EditorInfo.IME_ACTION_SEARCH),Toast.LENGTH_SHORT).show();
//                if (actionId== EditorInfo.IME_ACTION_SEARCH){
//                    ((Button)findViewById(R.id.btnStartSearch)).performClick();
//                    Toast.makeText(getApplicationContext(),"Search",Toast.LENGTH_SHORT).show();
//                }
//                return true;
//            }
//        });
        /*prepare database*/
        MyDatabase_Dishes database_dishes = new MyDatabase_Dishes(getBaseContext());
        /*search from database*/
        ArrayList<Object> searchedDishesObjectList = database_dishes.SearchDatabase("*", String.format("dishesName like '%%%s%%' limit 5", keyword));
        for (Object object : searchedDishesObjectList) {
            /*prepare adapter*/
            String foodName = ((MyDatabase_Dishes.FieldsDishes) object).dishesName;
            //all material = main ingredient+minor ingredient
            String allMaterial = ((MyDatabase_Dishes.FieldsDishes) object).mainIngredient + ((MyDatabase_Dishes.FieldsDishes) object).minorIngredient;
            int id = ((MyDatabase_Dishes.FieldsDishes) object).dishesID;
            /*calc if this food is good to eat*/
            String[] arrAllMaterial = allMaterial.replace(" ", "").split(";");
            ArrayList<String> listMaterial = new ArrayList<String>();
            for (String str : arrAllMaterial) {
                if (str.equals("")) continue;
                listMaterial.add(str.split(",")[0]);
            }

            /*add*/
            if (onlyOneNameSearchedContainer.add(foodName))  //if you want to show all result,del this.
                resultList.add(new listResultAdapter.SearchFoodResult(foodName, Practical.isDishesSuitable(listMaterial, SearchActivity.this), id, Config.DISHES));
        }
    }

    /**
     * Search Material
     */
    public void doSearchMaterial() {
        /*get word*/
        String keyword = ((EditText) findViewById(R.id.editKeyword)).getText().toString();
        /*prepare database*/
        MyDataBase_T_FOODS dataBase_t_foods = new MyDataBase_T_FOODS(getBaseContext());
        /*search from database*/
        ArrayList<MyDataBase_T_FOODS.T_FOODS> searchedFoodsList = dataBase_t_foods.SearchT_FOODS("*", String.format("Name like '%%%s%%' limit 10", keyword));
        for (MyDataBase_T_FOODS.T_FOODS food : searchedFoodsList) {
            /*prepare adapter*/
            String foodName = ((MyDataBase_T_FOODS.T_FOODS) food).NAME;
            /*get id*/
            int id = ((MyDataBase_T_FOODS.T_FOODS) food)._ID;
            /*calc if this food is good to eat*/
            int isGoodToEat = Practical.isFoodSuitable(id, getApplicationContext());
            /*add*/
            if (onlyOneNameSearchedContainer.add(foodName))  //if you want to show all result,del this.
                resultList.add(new listResultAdapter.SearchFoodResult(foodName, isGoodToEat, id, Config.MATERIAL));
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.search, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


}
